package com.xy.controller;

import com.xy.service.DeferredResultQueue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * @author 谢阳
 * @version 1.8.0_131
 * @date 2022/4/11 12:49
 * @description
 */

@Controller
public class AsyncController {

    @RequestMapping("/createOrder")
    @ResponseBody
     public DeferredResult<Object> createOrder() {

        DeferredResult<Object> objectDeferredResult = new DeferredResult<>(3000L,"create fail...");

        DeferredResultQueue.save(objectDeferredResult);

        return objectDeferredResult;
     }

     @ResponseBody
     @RequestMapping("/create")
     public String create() {
         String order = UUID.randomUUID().toString();
         DeferredResult<Object> objectDeferredResult = DeferredResultQueue.get();
         objectDeferredResult.setResult(order);
         return "success====>" + order;
     }

    @RequestMapping("/async01")
    @ResponseBody
    public Callable<String> async01() {
        System.out.println(Thread.currentThread() + "主线程start===>" + System.currentTimeMillis());
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println(Thread.currentThread() + "副线程start===>" + System.currentTimeMillis());
                Thread.sleep(3000);
                System.out.println(Thread.currentThread() + "副线程end===>" + System.currentTimeMillis());
                return "Callable<String> async01()";

            }
        };
        System.out.println(Thread.currentThread() + "主线程end===>" + System.currentTimeMillis());
        return callable;
    }
}
